<template>
  <basic-container>
    <el-row :gutter="24" class="user-info">
      <el-col :span="6" style="padding-right: 0px;">
        <el-card class="border-card" shadow="never">
          <div slot="header" class="clearfix">
            <h4 class="el-card__title">组织机构树</h4>
          </div>
          <ul id="organTree" class="ztree" style="min-height: 580px; max-height:580px; overflow: auto"></ul>
        </el-card>
      </el-col>
      <el-col :span="18" style="padding-left: 0px;">
        <el-card class="border-card user-list-card" shadow="never">
          <div slot="header">
            <h4 class="el-card__title">用户列表</h4>
            <el-button type="primary"
                       icon="el-icon-plus"
                       @click="handleAdd"
                       :disabled="addDisabled"
                       size="small"
                       style="margin-left: 20px;">新增
            </el-button>
            <el-button type="primary"
                       icon="el-icon-user"
                       @click="handleRole"
                       :disabled="setDisabled"
                       size="small"
                       style="margin-left: 20px;">角色配置
            </el-button>
            <div class="el-card__tool" @keyup.enter="querySearch">
              <el-input placeholder="请输入查询条件" size="mini" style="width:300px;" v-model="queryStream">
                <el-button slot="append" size="mini" icon="el-icon-search" @click="querySearch"></el-button>
              </el-input>
            </div>
          </div>
          <avue-crud ref="crud"
                     class="user-list"
                     :option="option"
                     :data="data"
                     v-model="ruleForm"
                     :page="page"
                     :before-open="beforeOpen"
                     @on-load="onLoad"
                     @row-save="rowSave"
                     @row-update="rowUpdate"
                     @selection-change="selectionChange"
                     @current-change="currentChange"
                     @size-change="sizeChange"
                     style="min-height: 580px;">
            <template slot-scope="scope" slot="menu">
              <el-button type="text"
                         icon="el-icon-edit"
                         size="small"
                         @click.stop="rowEdit(scope.row, scope.index)">编辑
              </el-button>
              <el-button type="text"
                         icon="el-icon-remove-outline"
                         size="small"
                         v-if="scope.row.status == '1'"
                         @click="rowStop(scope.row,scope.index)">停用
              </el-button>
              <el-button type="text"
                         icon="el-icon-circle-check"
                         size="small"
                         v-if="scope.row.status == '0'"
                         @click="rowStart(scope.row,scope.index)">启用
              </el-button>
              <el-button type="text"
                         icon="el-icon-refresh"
                         size="small"
                         @click.stop="rowPass(scope.row, scope.index)">重置密码
              </el-button>
            </template>
          </avue-crud>
          <el-dialog title="用户角色配置"
                     :visible.sync="box"
                     width="20%">
            <el-tree :data="list"
                     show-checkbox
                     node-key="id"
                     ref="tree"
                     :default-checked-keys="defaultObj"
                     :props="props">
            </el-tree>
            <span slot="footer" class="dialog-footer">
        <el-button @click="box = false">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
          </el-dialog>
        </el-card>
      </el-col>
    </el-row>
  </basic-container>
</template>
<script>
  import $ from 'jquery'
  import { organTree } from "@/api/organ/organ";
  import { getList, verifyUnique, userTree, add, detail, update, reset, grantRole, userRole, grant } from "@/api/user/user";
  import { mobileRule, idCardRule, emailRule } from '@/util/validate'
  import { sm3Encrypt, sm4Encrypt, sm4Decrypt } from '@/util/smcrypto'

  export default {
    name: "user-info",
    inheritAttrs: false,
    data() {
      const validCode = (rule, value, callback) => {
        let data = {value: value};
        if (this.ruleForm.id) {
          data = {value: value, id: this.ruleForm.id};
        }
        verifyUnique(data).then(data => {
          if (!data.success)
            callback(new Error('此用户账号已被使用!'))
          else
            callback()
        })
          .catch(err => {
            console.log(err)
            callback(new Error('验证失败!'))
          })
      };
      return {
        addDisabled: true,
        setDisabled: true,
        treeData: [],
        setting: {
          view: {
            showIcon: false
          },
          data: {
            key: {
              name: "title"
            },
            simpleData: {
              enable: true,
              idKey: "id",
              pIdKey: "parentId",
              rootPId: "",
              nodeType: "type",
              regionId: "regionId",
              regionName: "regionName"
            }
          },
          callback: {
            onClick: this.zTreeOnClick,
          }
        },
        zTree: {},
        queryStream: '',
        query: {},
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        option: {
          border: true,
          selection: true,
          reserveSelection: true,
          tip: false,
          addBtn: false,
          columnBtn: false,
          refreshBtn: false,
          searchBtn: false,
          editBtn: false,
          delBtn: false,
          index: false,
          indexLabel: '序号',
          size: 'small',
          // dialogHeight: 350,
          menuWidth: 200,
          column: [
            {
              label: "登录账号",
              prop: "account",
              search: false,
              maxlength: 32,
              rules: [
                {required: true, message: '请输入登录账号', trigger: 'blur'},
                {min: 3, max: 32, message: '长度在 3 到 32 个字符'},
                {pattern: /^[a-zA-Z0-9_]{3,32}$/, message: '请输入3-32个字符，允许输入字母、数字、下划线'},
                {validator: validCode, trigger: 'blur'}
              ]
            },
            {
              label: "登录密码",
              prop: "pwd",
              type: "password",
              search: false,
              editDisplay: false,
              hide: true,
              maxlength: 32,
              width: 100,
              rules: [
                {required: true, message: '请输入登录密码', trigger: 'blur'},
                {min: 6, message: '密码必须至少为 6 个字符'},
              ]
            },
            {
              label: "姓名",
              prop: "name",
              search: false,
              width: 100,
              rules: [
                {required: true, message: '请输入用户姓名', trigger: 'blur'},
                {min: 2, max: 32, message: '长度在 2 到 32 个字符'},
              ]
            },
            {
              label: "手机号码",
              prop: "mobile",
              search: false,
              hide: true,
              rules: [
                {required: true, message: '请输入手机号码', trigger: 'blur'},
                { validator: mobileRule, trigger: 'blur' },
              ]
            },
            {
              label: "身份证号",
              prop: "cardNo",
              search: false,
              hide: true,
              rules: [
                {required: true, message: '请输入身份证号', trigger: 'blur'},
                { validator: idCardRule, trigger: 'blur' },
              ]
            },
            {
              label: "邮箱",
              prop: "email",
              search: false,
              hide: true,
              rules: [
                { validator: emailRule, trigger: 'blur' },
              ]
            },
            {
              label: "",
              prop: "regionId",
              hide: true,
              display: false,
            },
            {
              label: "所属区划",
              prop: "regionName",
              disabled: true,
              width: 100,
              rules: [
                { required: true, message: "请选择所属区划", trigger: "blur" }
              ]
            },
            {
              label: "",
              prop: "organId",
              hide: true,
              display: false,
            },
            {
              label: "所属组织",
              prop: "organName",
              addDisplay: false,
              editDisplay: false,
              viewDisplay: false,
            },
            {
              label: "",
              prop: "organIdPath",
              hide: true,
              display: false,
            },
            {
              label: "所属组织",
              prop: "organNamePath",
              hide: true,
              disabled: true,
              rules: [
                { required: true, message: "请选择所属组织", trigger: "blur" }
              ]
            },
            {
              label: "",
              prop: "directOrganId",
              hide: true,
              display: false,
            },
            {
              label: "",
              prop: "directOrganName",
              hide: true,
              display: false,
            },
            {
              label: "上级",
              prop: "parentId",
              // formslot: true,
              type: "tree",
              dicData: [],
              search: false,
              hide: true,
              props: {
                value: 'id',
                label: "title",
              },
            },
            {
              label: "昵称",
              prop: "nickName",
              search: false,
              hide: true
            },
            {
              label: "职务",
              prop: "position",
              search: false,
              hide: true
            },
            {
              label: "排序",
              prop: "sortOrder",
              type: 'number',
              span: 8,
              search: false,
              hide: true,
              value: 1,
              minRows: 1,
              maxRows: 999
            },
            {
              label: "用户说明",
              prop: "remark",
              type: "textarea",
              search: false,
              hide: true,
              minWidth: '200',
              span: 24,
              minRows: 3
            },
          ],
        },
        data: [],
        ruleForm: {
          password: ''
        },
        selData: [],
        box: false,
        props: {
          label: "title",
          value: "key"
        },
        list: [],
        defaultObj: [],
        userIds: '',
      }
    },
    created() {
      this.getOrganTree();
    },
    methods: {
      getOrganTree() {
        this.addDisabled = true;
        this.treeData = [];
        organTree().then(res => {
          this.treeData = res.data;
          $.fn.zTree.init($("#organTree"), this.setting, this.treeData);
          this.zTree = $.fn.zTree.getZTreeObj("organTree");
          if (this.query.nodeId) {
            var node = this.zTree.getNodeByParam("id", this.query.nodeId);
            if (node) {
              this.zTree.selectNode(node);
              // this.zTree.expandNode(node, true, false);
            }
          }
        });
      },
      beforeOpen(done, type) {
        // 获取上级
        const index = this.$refs.crud.findColumnIndex("parentId");
        if (["edit", "view"].includes(type)) {
          userTree(this.ruleForm.id, this.ruleForm.regionId).then(res => {
            this.setTreeDisabled(res.data);
            this.option.column[index].dicData = res.data;
          });
        } else {
          userTree("", this.query.regionId).then(res => {
            this.setTreeDisabled(res.data);
            this.option.column[index].dicData = res.data;
          });
        }
        done();
      },
      handleAdd() {
        if (this.zTree.getNodes().length > 0 && (!this.query.nodeType || this.query.nodeType == "0" || this.query.nodeType == "1")) {
          this.$message({
            type: "error",
            message: "请先选择新增用户的所属组织"
          });
          return;
        }
        const rgidIndex = this.$refs.crud.findColumnIndex("regionId");
        this.option.column[rgidIndex].value = this.query.regionId;
        const rgnameIndex = this.$refs.crud.findColumnIndex("regionName");
        this.option.column[rgnameIndex].value = this.query.regionName;
        if (this.query.nodeType !== '0' && this.query.nodeType !== "1") {
          const dorgIdIndex = this.$refs.crud.findColumnIndex("directOrganId");
          this.option.column[dorgIdIndex].value = this.query.nodeId;
          const dorgNameIndex = this.$refs.crud.findColumnIndex("directOrganName");
          this.option.column[dorgNameIndex].value = this.query.nodeName;

          const orgIdIndex = this.$refs.crud.findColumnIndex("organId");
          const orgNameIndex = this.$refs.crud.findColumnIndex("organName");
          const orgIdPathIndex = this.$refs.crud.findColumnIndex("organIdPath");
          const orgNamePathIndex = this.$refs.crud.findColumnIndex("organNamePath");

          var sNodes = this.zTree.getSelectedNodes();
          if (sNodes.length > 0) {
            var nodes = sNodes[0].getPath();
            let disId = "";
            let disName = "";
            let orgId = "";
            let orgName = "";
            for (let i = 0; i < nodes.length; i++) {
              if (nodes[i].type == "0" || nodes[i].type == "1") {
                continue;
              }
              if (nodes[i].type == "2") {
                orgId = nodes[i].id;
                orgName = nodes[i].title;
              }
              if (i == nodes.length -1) {
                disId += nodes[i].id;
                disName += nodes[i].title;
              } else {
                disId += nodes[i].id + "#";
                disName += nodes[i].title + "#";
              }
            }
            this.option.column[orgIdIndex].value = orgId;
            this.option.column[orgNameIndex].value = orgName;
            this.option.column[orgIdPathIndex].value = disId;
            this.option.column[orgNamePathIndex].value = disName;
          }
        }
        this.$refs.crud.rowAdd();
      },
      zTreeOnClick(event, treeId, treeNode) {
        this.handleNodeClick(treeNode);
      },
      onLoad(page, params = {}) {
        this.selData = [];
        this.setDisabled = true;
        getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data;
          this.page.total = data.total;
          this.data = data.records;
        });
      },
      handleNodeClick(treeNode) {
        this.queryStream = '';
        this.query.nodeId = treeNode.id;
        this.query.nodeName = treeNode.title;
        this.query.nodeType = treeNode.type;
        this.query.regionId = treeNode.regionId;
        this.query.regionName = treeNode.regionName;
        this.query.query = "";
        this.page.currentPage = 1;
        if (treeNode.type !== "0" && treeNode.type !== "1") {
          this.addDisabled = false;
        } else {
          this.addDisabled = true;
        }
        this.onLoad(this.page, this.query);
      },
      rowSave(row, loading, done) {
        this.ruleForm.password = sm3Encrypt(this.ruleForm.pwd);
        this.ruleForm.mobile = sm4Encrypt(this.ruleForm.mobile);
        this.ruleForm.cardNo = sm4Encrypt(this.ruleForm.cardNo);
        add(this.ruleForm).then(ret => {
          if (ret.success) {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        })
      },
      rowEdit(row, index) {
        detail(row)
          .then(res => {
            let data = res.data;
            if (data.mobile) {
              data.mobile = sm4Decrypt(data.mobile);
            }
            if (data.cardNo) {
              data.cardNo = sm4Decrypt(data.cardNo);
            }
            this.$refs.crud.rowEdit(data, index);
          })
          .catch(() => {
            this.$message.error("获取用户信息失败");
          });
      },
      rowUpdate(row, index, loading, done) {
        this.ruleForm.mobile = sm4Encrypt(this.ruleForm.mobile);
        this.ruleForm.cardNo = sm4Encrypt(this.ruleForm.cardNo);
        update(this.ruleForm).then(ret => {
          if (ret.success) {
            loading();
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          } else {
            done();
            this.$message({
              type: "error",
              message: ret.msg
            });
          }
        }, error => {
          done();
          console.log(error);
        });
      },
      rowStop(row, index) {
        this.$confirm("确定要停用该用户吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            row.status = "0";
            return update(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      rowStart(row, index) {
        this.$confirm("确定要启用该用户吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            row.status = "1";
            return update(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      rowPass(row, index) {
        this.$confirm("确定要重置该用户密码吗?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            row.status = "1";
            return reset(row);
          })
          .then(ret => {
            if (ret.success) {
              this.onLoad(this.page);
              this.$message({
                type: "success",
                message: "操作成功!"
              });
            } else {
              this.$message({
                type: "error",
                message: ret.msg
              });
            }
          }).catch(() => {
        });
      },
      selectionChange(list) {
        this.selData = list;
        if (this.selData.length >= 1) {
          this.setDisabled = false;
        }
      },
      handleRole() {
        if (this.selData.length < 1) {
          this.$message({
            type: "error",
            message: "请选择用户"
          });
          return;
        }

        let ids = "";
        for(let item of this.selData) {
          ids += item.id + ",";
        }

        this.userIds = ids.substr(0, ids.length-1);
        this.defaultObj = [];
        grantRole()
          .then(res => {
            this.list = res.data;
            return userRole(this.userIds);
          })
          .then(res => {
            this.defaultObj = res.data;
            this.box = true;
          });
      },
      submit() {
        const roleIds = this.$refs.tree.getCheckedKeys().join(",");
        grant(this.userIds, roleIds).then(() => {
          this.box = false;
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.selectClear();
          this.onLoad(this.page);
        });
      },

      currentChange(currentPage) {
        this.page.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.page.pageSize = pageSize;
      },
      querySearch() {
        this.query.query = this.queryStream;
        this.page.currentPage = 1;
        this.onLoad(this.page, this.query);
      },
      setTreeDisabled(data) {
        let that = this
        for (let i of data) {
          if (i.type !== '9') {
            i.disabled = true;
          }
          if (i.children) {
            that.setTreeDisabled(i.children)
          }
        }
      }
    }
  }
</script>
<style scoped lang="scss">
  @import "~_s/placeholders";
  @import '~_s/table-list';
  ::v-deep .user-list {
    @extend %fullsize;
    @extend %table-list;
    .avue-crud__menu {
      display: none;
    }
  }
  ::v-deep .user-info {
    .el-card {
      .el-card__header {
        padding: 5px 15px;
      }
      .el-card__title {
        font-size: 14px;
      }
    }
  }

</style>